package com.aube.utils;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.R;
import com.aube.model.Upgrade;
import com.aube.model.UpgradeModel;
import com.huyn.baseframework.net.BFJSONRequest;
import com.huyn.baseframework.net.HttpRequestLoader;
import com.huyn.baseframework.net.NetStateHelper;
import com.huyn.baseframework.net.OpenApi;
import com.huyn.baseframework.utils.Constant;
import com.huyn.baseframework.utils.StorageUtil;
import com.huyn.baseframework.utils.Utils;

import java.io.File;
import java.util.HashMap;

public class UpgradeUtil {

    public static final String APP_CLOSE = "APP_CLOSE";

    private DownloadManager downloadManager;
    private DownloadUtil downloadUtil;
    private long downloadId;
    private File downloadFile;
    private CompleteReceiver completeReceiver;

    /**
     * 升级
     **/
    public void upGrade(final Activity context, final boolean showToast) {
        HashMap<String, String> postdata = new HashMap<String, String>();
        postdata.put("tag", "android");
        postdata.put(OpenApi.API_METHOD, OpenApi.UPGRADE);
        BFJSONRequest request = new BFJSONRequest(UpgradeModel.class, postdata, new Response.Listener<UpgradeModel>() {

            @Override
            public void onResponse(UpgradeModel response) {
                if (response != null && response.success())
                    dealUpGrade(context, response.data, showToast);
            }

            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onStart() {
            }
        });

        request.setTimeOut(5000);
        HttpRequestLoader.getInstance(context).startCacheLoader("", request, true);
    }

    private void dealUpGrade(final Activity mthis, final Upgrade upGrade, final boolean showToast) {
        int UPDATE_LEVEL = "Y".equalsIgnoreCase(upGrade.forceUpd) ? Constant.UPDATE_FORC : Constant.UPDATE_SPECIFIC;

        //本地version比服务器version大,直接忽略
        int state = Constant.APP_VERSION.compareTo(upGrade.curAppVersion);
        if (state >= 0)
            return;

        //非wifi情况下不强制升级
        if (UPDATE_LEVEL == Constant.UPDATE_FORC && !NetStateHelper.isWifiConnected(mthis))
            UPDATE_LEVEL = Constant.UPDATE_SPECIFIC;

        if (UPDATE_LEVEL == Constant.UPDATE_NOTING) {
            if (showToast) {
                Utils.showToast(mthis, "已经是最新版");
            }
        } else if (UPDATE_LEVEL == Constant.UPDATE_FORC) {
            Builder builder = new Builder(mthis, R.style.AlertDialog);
            builder.setMessage(upGrade.updDesc)
                    .setPositiveButton("立即升级",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    downFile(upGrade, mthis, false);
                                    mthis.finish();
                                }
                            }).show().setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface arg0) {
                    mthis.sendBroadcast(new Intent(APP_CLOSE));
                }
            });

        } else if (UPDATE_LEVEL == Constant.UPDATE_SPECIFIC) {
            new Builder(mthis, R.style.AlertDialog)
                    .setMessage(upGrade.updDesc)
                    .setNegativeButton("以后再说",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();
                                }
                            })
                    .setPositiveButton("立即升级",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    downFile(upGrade, mthis, true);
                                }
                            }).show();
        }

    }

    class CompleteReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            if (completeDownloadId == downloadId) {
                if (downloadUtil.getStatusById(downloadId) == DownloadManager.STATUS_SUCCESSFUL) {
                    install(context);
                }
            }
        }
    }

    public void install(Context context) {
        try {
            if (completeReceiver != null)
                context.unregisterReceiver(completeReceiver);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            //intent.setDataAndType(downloadManager.getUriForDownloadedFile(downloadId), downloadManager.getMimeTypeForDownloadedFile(downloadId));//有些手机(华为)会返回application/octet-stream
            intent.setDataAndType(downloadManager.getUriForDownloadedFile(downloadId), "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            Utils.showToast(context, "自动安装失败, 请点击<通知栏>项目进行安装");
        }
    }

    void downFile(final Upgrade upGrade, final Context mthis, boolean registerListener) {
        downloadManager = (DownloadManager) mthis.getSystemService(Context.DOWNLOAD_SERVICE);
        downloadUtil = new DownloadUtil(downloadManager);
        completeReceiver = new CompleteReceiver();
        boolean canUseSDCard = StorageUtil.checkSDWritePermission(mthis);
        File sdcard = Environment.getExternalStorageDirectory();
        if (sdcard.exists() && canUseSDCard) {
//		if (Environment.getExternalStorageState().equals(
//				Environment.MEDIA_MOUNTED)) {
            //有外部存储
            downloadFile = new File(sdcard + Constant.UPDATE_APK_DIR,
                    Constant.UPDATE_APK_NAME_PREFIX
                            + upGrade.curAppVersion
                            + Constant.UPDATE_APK_NAME_SUFIX);
            try {

                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(upGrade.url));
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, downloadFile.getName());
                request.setTitle(mthis.getString(R.string.app_name));
                request.setDescription(mthis.getString(R.string.downloading));
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setVisibleInDownloadsUi(false);
                downloadId = downloadManager.enqueue(request);

                if (registerListener)
                    mthis.registerReceiver(completeReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
            } catch (Exception e) {
                e.printStackTrace();
                Utils.showToast(mthis, "自动更新失败, 请从应用商店下载更新");
            }
        } else {
            //无外部存储用内存
            downloadFile = new File(mthis.getFilesDir(), Constant.UPDATE_APK_NAME_PREFIX
                    + upGrade.curAppVersion
                    + Constant.UPDATE_APK_NAME_SUFIX);

            Utils.showToast(mthis, "自动更新失败, 请从应用商店下载更新");
        }
    }

}
